package com.badibadi.mytools;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.badibadi.infos.SinaSource;
import com.badibadi.infos.SinaSourceModel;
import com.badibadi.uniclubber.R;
import com.badibadi.uniclubber.SinaExpressionActivity;
import com.badibadi.uniclubber.SinaExpressionActivity.MyListAdapter;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

/**
 * sina表情工具
 * @author Administrator
 *
 */
public class SinaExpressionTools {

	ViewPager viewPager;
	List<View> gridViewList; //裝載gridview的容器
	List<SinaSourceModel> listInfo; //总数据
	int page;//viewpager的頁數
	Context context;
	SinaSource sina=new SinaSource();
	private DisplayImageOptions options;
	
	
//	private String UimgPath;
	
	public SinaExpressionTools(Context context,ViewPager viewPager)
	{
		this.context=context;
		this.viewPager=viewPager;
		
		
		options = new DisplayImageOptions.Builder()
		.showStubImage(R.drawable.ic_stub)
		.showImageForEmptyUri(R.drawable.noimage)
		.showImageOnFail(R.drawable.noimage).cacheInMemory()
		.cacheOnDisc().displayer(new RoundedBitmapDisplayer(5)).build();
		//裝載所有顯示數據得容器
		listInfo = new ArrayList<SinaSourceModel>();
		//裝載gridview的容器
		gridViewList = new ArrayList<View>();
		listInfo = sina.getSinaSource();
		//获取所有数据的总长
		int size = listInfo.size();
		if (size == 0) return;
		
		//確定viewpager的頁數
		int len = size / 21 ;
		if(size % 21  == 0){
			page = len;
		}else{
			page = len + 1;
		}
		
		//為viewpager裝配數據
//		viewPager = (ViewPager) findViewById(R.id.viewpagerLayout);
	
		viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
			@Override
			public void onPageSelected(int pages) {}
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {}
			@Override
			public void onPageScrollStateChanged(int page) {}
		});
		
		
		
		viewPager.setAdapter(new MyPagerAdapter());
	}
	/**
	 * 将sinaSource中的字符串进行转换成img路径
	 * @param sinaSource
	 * @return  
	 */
	public static String toImgPath(String sinaSource)
	{
		String imgpath1="";
		if(sinaSource.indexOf("src='")!=-1)
		{
			int a=sinaSource.indexOf("src='");
			imgpath1=sinaSource.substring(a+5, sinaSource.length()-4);
		}
		return imgpath1; 
	}
//	Context context = SinaExpressionActivity.this;】
	/**
	 * 替换SinaSource里的所有的replace 为path
	 * path类似<src=  >;
	 * replace类似[开心]
	 * @return
	 */
	public static String replaceAllReplaceToPath(String source)
	{
//		   
		String str=source;
		SinaSource s=new SinaSource();
		
		List<SinaSourceModel> listInfo=s.getSinaSource();
		for(int i=0;i<listInfo.size();i++)
		{
//			   
			if(str.indexOf(listInfo.get(i).getReplace())!=-1)
			{
//				   
				String rep=listInfo.get(i).getReplace().substring(0, listInfo.get(i).getReplace().length()-1);
//				   
				String rep2="\\"+rep+"\\]";
//				   
				str=str.replaceAll(rep2, listInfo.get(i).getPath());
//				   
			}
		}
//		   
//		str=str.replaceAll("\\[", "");
//		str=str.replaceAll("\\]", "");
		return str;
	}
	
	/**
	 * 替换SinaSource里的所有的path为 replace 
	 * path类似<src=  >;
	 * replace类似[开心]
	 * @return
	 */
	public static String replaceAllPathToReplace(String source)
	{
//		   
		String str=source;
		SinaSource s=new SinaSource();
		
		List<SinaSourceModel> listInfo=s.getSinaSource();
		for(int i=0;i<listInfo.size();i++)
		{
//			   
			if(str.indexOf(listInfo.get(i).getPath())!=-1)
			{
//				   
				String rep=listInfo.get(i).getReplace();
//				   
//				String rep2="\\"+rep+"\\]";
//				   
				str=str.replaceAll(listInfo.get(i).getPath(),rep);
//				   
			}
		}
//		   
//		str=str.replaceAll("\\[", "");
//		str=str.replaceAll("\\]", "");
		return str;
	}
	
	/**
	 * viewpager的數據
	 * @author Administrator
	 *
	 */
	class MyPagerAdapter extends PagerAdapter{
		public MyPagerAdapter() {
			//viewpage所需要的界面
			for (int i = 0; i < page ; i++) {
				//第三步：使用gridview来装已安装的apk
				GridView gridView = new GridView(context);
				gridView.setNumColumns(7);
				gridView.setAdapter(new MyListAdapter(i));
				gridViewList.add(gridView);
			}
		}
		@Override
		public int getCount() {
			return page;//总页数
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			((ViewPager) container).removeView((View) object);
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			View view = gridViewList.get(position);
			container.addView(view);
			return view;
		}
		
	}
	
	/**
	 * gridview的數據
	 * @author Administrator
	 *
	 */
	public class MyListAdapter extends BaseAdapter{
		
		ArrayList<SinaSourceModel> gridInfo;
		public MyListAdapter(int page){
			gridInfo = new ArrayList<SinaSourceModel>();
			for(int i = page* 21; i<page* 21+21 ;i++){
				if(i == listInfo.size()) break;
				gridInfo.add(listInfo.get(i));
			}
		}
		@Override
		public int getCount() {
			return gridInfo == null? 0:gridInfo.size();
		}

		@Override
		public Object getItem(int position) {
			return gridInfo == null? null:gridInfo.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		ViewHolder holder = null;
		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			//1、如果没有可利用item时，找出所有控件
			if(convertView == null){
				holder = new ViewHolder();
				convertView = ((Activity) context).getLayoutInflater().inflate(R.layout.gridview_item, parent, false);
				holder.iconiView = (ImageView) convertView.findViewById(R.id.image);
//				holder.textView = (TextView) convertView.findViewById(R.id.text);
			//2、绑定
				convertView.setTag(holder);
			}else{//3、有可利用的item时就获取赋值使用
				holder = (ViewHolder) convertView.getTag();
			}
			
			
			//4、赋值
			String info = gridInfo.get(position).getPath();
//			   
			//对sina表情进行一次截取处理
			String info2=SinaExpressionTools.toImgPath(info);
			ImageLoader.getInstance().displayImage(info2, holder.iconiView, options);
			
//			holder.iconiView.setImageDrawable(info.activityInfo.loadIcon(getPackageManager()));
//			holder.textView.setText(info.activityInfo.loadLabel(getPackageManager()));//获取应用名
			//监听点击事件
			holder.iconiView.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
//					String info = gridInfo.get(position);
//					//获取包名
//					String packageName = info.activityInfo.packageName;
//					//获取activity类
//					String activityName = info.activityInfo.name;
//					//根据包名和activity来启动程序
//					ComponentName component = new ComponentName(packageName, activityName);
//					Intent intent = new Intent();
//					intent.setComponent(component);
//					startActivity(intent);
				}
			});
			return convertView;
		}
		private class ViewHolder {
			ImageView iconiView;
//			TextView textView;
		}
	}
	/**
	 * 获取网络图片,如果图片存在缓存中，就返回该图片，否者从网络中加载图片并且缓存起来
	 * @param path
	 * @return
	 */
public static Uri getImage(String path,File cacheDir) throws Exception{//path--》md5--》字符串。jpg（经过md5加密得到一个32位的字符串）
	// TODO Auto-generated method stub
   File localFile=new File(cacheDir,MD5.getMD5(path)+path.substring(path.lastIndexOf(".")));
   if(localFile.exists())
   {
	   return Uri.fromFile(localFile);
   }else
   {
	   HttpURLConnection conn=(HttpURLConnection) new URL(path).openConnection();
		conn.setConnectTimeout(5000);//设置延迟5s
		conn.setRequestMethod("GET");//设置请求方式
		if(conn.getResponseCode()==200)//获取返回的数。200成功
		{
		  FileOutputStream outStream=new FileOutputStream(localFile);
		  InputStream inputStream=conn.getInputStream();
		  byte[] buffer=new byte[1024];
		  int len=0;
		  while((len=inputStream.read(buffer))!=-1)
		  {
			  outStream.write(buffer,0,len);
		  }
		  inputStream.close();
		  outStream.close();
		  return Uri.fromFile(localFile);
		}
   }
   
	
	
	return null;
}
	/**
	 * 第二部：获取所有安装的apk
	 */
	public List<ResolveInfo> getInstallAPK() {
		Intent intent = new Intent(Intent.ACTION_MAIN,null);
		intent.addCategory(Intent.CATEGORY_LAUNCHER);
		return context.getPackageManager().queryIntentActivities(intent, 0);
	}
	/**
     * 得到网页中图片的地址
     */
    public static List<String> getImgSrcList(String htmlStr) {
        List<String> pics = new ArrayList<String>();

        String regEx_img = "<img.*?src=\"http://(.*?).jpg\""; // 图片链接地址
        Pattern p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
        Matcher m_image = p_image.matcher(htmlStr);
        while (m_image.find()) {
            String src = m_image.group(1);
            if (src.length() < 100) {
                pics.add("http://" + src + ".jpg");
            }
        }
        return pics;
    }
	
}
